<?php
/**
 * Class name is ConfigFunctionlogSearch * @package backend\modules\common\controllers;
 * @author  Womtech  email:chareler@163.com
 * @DateTime 2020-04-14 23:27 
 */

namespace common\models\log;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\db\ActiveQuery;
use yii\db\Expression;
use yii\helpers\ArrayHelper;
use common\models\log\ConfigFunctionlog;

/**
 * ConfigFunctionlogSearch represents the model behind the search form about `common\models\log\ConfigFunctionlog`.
 */
class ConfigFunctionlogSearch extends ConfigFunctionlog
{
    const EMPTY_STRING = "(空字符)";
    const NO_EMPTY = "(非空)";
    const SCENARIO_EDITABLE = 'editable';

    public $start;
    public $end;
    public $pageSize;
    public $page;
    public $usernames;

    protected $arrBindValues=[];

    public function scenarios()
    {
        return ArrayHelper::merge(parent::scenarios(), [
            self::SCENARIO_EDITABLE => [],
        ]);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'merchant_id', 'user_id', 'error_code'], 'integer'],
            [['app_id', 'method', 'module', 'controller', 'action', 'url', 'get_data', 'post_data', 'header_data', 'ip', 'error_msg', 'error_data', 'req_id', 'user_agent', 'device', 'device_uuid', 'device_version', 'device_app_version', 'status'], 'safe'],
            /* [['created_at', 'updated_at'], 'match', 'pattern' => '/^.+\s\-\s.+$/'], */

            [['start', 'end'],  'date', 'format' => 'yyyy-MM-dd', 'on' => 'search'],
            [['pageSize', 'page'], 'integer', 'on' => 'search'],
            [['usernames'], 'string', 'on' => 'search'],

        ];
    }
    /**
     * 创建时间  如果不需要或者该数据模型 没有 created_at 字段，您应该删除
     * @return array|false|int
     */
    public function getCreatedAt()
    {
        if(empty($this->created_at)){
            return null;
        }
        $createAt = is_string($this->created_at)?strtotime($this->created_at):$this->created_at;
        if(date('H:i:s', $createAt)=='00:00:00'){
            return [$createAt, $createAt+3600*24];
        }
        return $createAt;
    }

/**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        //获取所有参数
        $this->load($params, '');

        //验证过滤及转义,系统自带规则,自定义规则,数据转化规则,都在rule中
        if (!$this->validate()) {
            return;
        }


        //查询执行开始
        //选用查询方式createCommand, 准备相关数据:分页相关,语句构成
        $rsCount =0;
        $rs =[];


        //初始化分页参数
        if (empty($this->pageSize)) {
            $this->pageSize = yii::$app->params['pageSize'];
        }
        $this->page =  !empty($this->page) ? (int)$this->page - 1 : 0;
        $rsStart = $this->page * $this->pageSize;
        //$rsEnd = ($this->page+1) * $this->pageSize;


        //sql语句,统计总数语句和查询语句的组成
        $sql = "";
        $countSql="";
        $sqlFields="";
        $sqlSelect = ""; 
        $sqlWhere =" where 1=1 ";   
        $sqlLimit ="";
        $sqlOrder ="  order by id desc";

        
        $sql .="select * from {{%config_functionlog}}";
        $sqlLimit =" limit $rsStart, $this->pageSize ";
        


        $sql .= $sqlSelect;
        $sql .= $this->toSqlWhere($params);
        $sql .= $sqlOrder;
        $sql .= $sqlLimit;
        

        $countSql .="select count(*) from {{%config_functionlog}}";
        $countSql .= $this->toSqlWhere($params);

        $sqlData = null;
        //$sqlData = yii::$app->db->createCommand($sql)->queryAll();


        

        $sqlStr = yii::$app->db->createCommand($sql)->bindValues($this->arrBindValues)->getRawSql();
        //$sqlStrTemp = yii::$app->db->createCommand($sql)->bindValues([])->getRawSql();

        //$rsCount = yii::$app->db->createCommand($countSql)->queryScalar();
        $rsCount = yii::$app->db->createCommand($countSql)->bindValues($this->arrBindValues)->queryScalar();
        //执行sql语句,获得数据
        $sqlData = yii::$app->db->createCommand($sql)->bindValues($this->arrBindValues)->queryAll();


        $data = [];
        $args = [
            [
                'inputFields' => ['user_id','created_id', 'updated_id'],
                'class' => '\common\models\Admin',
                'outFields' => ['user_id', 'username'],
                'keyField' => 'user_id',
                'relation' => [
                    'user_id' => ['toField' => 'username', 'outName' => 'visiter'],
                    'created_id' => ['toField' => 'username', 'outName' => 'creater'],
                    'updated_id' => ['toField' => 'username', 'outName' => 'updater'],
                ],
                'name' => 'idToUser'
            ]
        ];
        $sqlData = \common\helpers\ModelHelper::attachFieldsValue($sqlData, $args);

        //$rsCount = $sqlData->count();
        $rs['count'] = !empty($rsCount) ? $rsCount : 0;
        $rs['data'] = $sqlData;

        //查询执行结束


        //返回数据,格式array
        return $rs;
        
    } 

    protected function toSqlWhere($params){
        $sqlWhere =" where 1=1 ";
        if (!empty($this->start)) {
            $start = $this->start;
            $startTime = strtotime($start . " 00:00:00");
            //$sqlWhere .= " and created_at >= $startTime" ;
            $sqlWhere .= " and created_at >= :startTime " ;
            $this->arrBindValues[':startTime'] = $startTime ;
        }

        if (!empty($this->end)) {
            $end = $this->end;
            $endTime = strtotime($end . " 23:59:59");
            //$sqlWhere .= " and created_at <= $endTime" ;
            $sqlWhere .= " and created_at <= :endTime" ;
            $this->arrBindValues[':endTime']= $endTime;
        }

        if (!empty($this->usernames)) {
            $usernames = $this->usernames;
            
            //$sqlWhere .= " and name like '%$name%'" ;
            $sqlWhere .= " and created_id in (:usernames)" ;
            $this->arrBindValues[':usernames']= $usernames;
        }
        
        return $sqlWhere;

    }





    
    /**
     * Creates data provider instance with search query applied
     * @param array $params
     * @return ActiveDataProvider
     */
    public function search_bak($params)
    {
        $query = self::find();
        $this->load($params);
        if ( ! is_null($this->created_at) && strpos($this->created_at, ' - ') !== false ) {
            list($s, $e) = explode(' - ', $this->created_at);
            $query->andFilterWhere(['between', 'created_at', strtotime($s), strtotime($e)]);
        }
        if ( ! is_null($this->updated_at) && strpos($this->updated_at, ' - ') !== false ) {
            list($s, $e) = explode(' - ', $this->updated_at);
            $query->andFilterWhere(['between', 'updated_at', strtotime($s), strtotime($e)]);
        }
        $query->andFilterWhere([
            'id' => $this->id,
            'merchant_id' => $this->merchant_id,
            'user_id' => $this->user_id,
            'error_code' => $this->error_code,
        ]);
        $this->filterLike($query, 'app_id');
        $this->filterLike($query, 'method');
        $this->filterLike($query, 'module');
        $this->filterLike($query, 'controller');
        $this->filterLike($query, 'action');
        $this->filterLike($query, 'url');
        $this->filterLike($query, 'get_data');
        $this->filterLike($query, 'post_data');
        $this->filterLike($query, 'header_data');
        $this->filterLike($query, 'ip');
        $this->filterLike($query, 'error_msg');
        $this->filterLike($query, 'error_data');
        $this->filterLike($query, 'req_id');
        $this->filterLike($query, 'user_agent');
        $this->filterLike($query, 'device');
        $this->filterLike($query, 'device_uuid');
        $this->filterLike($query, 'device_version');
        $this->filterLike($query, 'device_app_version');
        $this->filterLike($query, 'status');;
        $dataProvider = new ActiveDataProvider([
            //'pagination' => ['pageSize' => 3,],
            'query' => $query,
            'sort' => ['defaultOrder' => ['id' => SORT_DESC]],
            ]);
        if (!$this->validate()) {
            return $dataProvider;
        }
        return $dataProvider;
    }

    /**
     * @param ActiveQuery $query
     * @param $attribute
     */
    protected function filterLike(&$query, $attribute)
    {
        $this->$attribute = trim($this->$attribute);
        switch($this->$attribute){
            case \Yii::t('app', '(not set)'):
                $query->andFilterWhere(['IS', $attribute, new Expression('NULL')]);
                break;
            case self::EMPTY_STRING:
                $query->andWhere([$attribute => '']);
                break;
            case self::NO_EMPTY:
                $query->andWhere(['IS NOT', $attribute, new Expression('NULL')])->andWhere(['<>', $attribute, '']);
                break;
            default:
                $query->andFilterWhere(['like', $attribute, $this->$attribute]);
                break;
        }
    }
}
